import pymongo
from pymongo.results import InsertOneResult,InsertManyResult,UpdateResult,DeleteResult
from bson import ObjectId

mongo_client = pymongo.MongoClient("127.0.0.1",27017)
db = mongo_client["DragonFire"]

# 增加
# res = db.users.insert_one({"name":"DragonFire"}) # type:InsertOneResult
# print(res,res.inserted_id)
# res = db.users.insert_many([{"name":"DragonFire"},{"name":"alexander"}]) # type:InsertManyResult
# print(res,res.inserted_ids)

# 查询
# res = db.users.find_one({"name":"DragonFire"})
# import json
# res["_id"] = str(res.get("_id"))
# json_str = json.dumps(res)
# loads_str = json.loads(json_str)
# res = db.users.find_one({"_id":ObjectId(loads_str.get("_id"))})
# # print(ObjectId("123123123123123123123123").from_datetime())
# print(res)
# # print(type(res.get("_id")))
# import json
# res = list(db.users.find({"name":"DragonFire"}))
# for index,item in enumerate(res):
# 	res[index]["_id"] = str(item.get("_id"))
# print(json.dumps(res))

# 改
# res = db.users.update_one({"name":"DragonFire"},{"$set":{"age":19}}) #type:UpdateResult
# print(res,type(res),res.upserted_id,res.raw_result)
# res = db.users.update_many({"name":"DragonFire"},{"$set":{"age":19}}) #type:UpdateResult
# print(res,type(res),res.raw_result)

# 删除：
# res = db.users.delete_one({"name":"alexander"}) # type:DeleteResult
# print(res.raw_result,res.deleted_count)
# res = db.users.delete_many({"name":"alexander"}) # type:DeleteResult
# print(res.raw_result,res.deleted_count)